<!-- 省市区联动组件 -->
<template>
  <nut-popup position="bottom" :style="{ height: '75%' }" :visible="props.showRound" @click-overlay="confirm"
    @click-close-icon="confirm">
    <nut-notify v-model:visible="toastShow" msg="省市区必选" />
    <nut-picker v-model="value" :columns="columns" title="城市选择" @confirm="confirm" @cancel="cancel"></nut-picker>
  </nut-popup>
</template>

<script setup lang="ts">
import { onMounted, defineComponent, getCurrentInstance, reactive, ref } from 'vue';
import { getAddressByCode } from "@/@api/wait"; // 待确认接口

import Taro from '@tarojs/taro';
import { IconFont } from '@nutui/icons-vue-taro';


const props = defineProps<{
  showRound: boolean
}>()

const emit = defineEmits(['receiveProvinceMsg'])

onMounted(() => {
  initAddressByCode(); // 获取省市区联动数据
})

const toastShow = ref(false);
const provinceMsg = ref(''); // 选择的省市区
// 初始化picker数据
const value = ref(['福建省', '福州市', '鼓楼区']);
const columns = ref([{
  text: '浙江',
  value: 'ZheJiang',
  children: [
    {
      text: '杭州',
      value: 'HangZhou',
      children: [
        { text: '西湖区', value: 'XiHu' },
        { text: '余杭区', value: 'YuHang' }
      ]
    },
    {
      text: '温州',
      value: 'WenZhou',
      children: [
        { text: '鹿城区', value: 'LuCheng' },
        { text: '瓯海区', value: 'OuHai' }
      ]
    }
  ]
},
{
  text: '福建',
  value: 'FuJian',
  children: [
    {
      text: '福州',
      value: 'FuZhou',
      children: [
        { text: '鼓楼区', value: 'GuLou' },
        { text: '台江区', value: 'TaiJiang' }
      ]
    },
    {
      text: '厦门',
      value: 'XiaMen',
      children: [
        { text: '思明区', value: 'SiMing' },
        { text: '海沧区', value: 'HaiCang' }
      ]
    }
  ]
}]);

// 获取省市区数据
async function initAddressByCode() {
  let params = {
    showallbranchs: "true",
    showonlyTF: "true"
  }
  const res = await getAddressByCode(params);
  if (res.statusCode == 200) {
    // console.log(res.data.info, '获取省市区联动')
    const reformattedData = recursiveReformat(res.data.info);
    columns.value = reformattedData;
  }
}

// 重组省市区数据
function recursiveReformat(data) {
  return data.map(item => ({
    text: item.name,
    value: item.name,
    ...(item.children && item.children.length > 0 ? { children: recursiveReformat(item.children) } : {})
  }));
}

// 点击省市区赋值给地址本抽屉
const confirm = ({ selectedValue, selectedOptions }) => {
  provinceMsg.value = selectedOptions.map((val) => val.text).join(',');
  console.log(provinceMsg.value, 'provinceMsg')
  emit('receiveProvinceMsg', provinceMsg.value);
};

const cancel = () => {
  if (!provinceMsg.value) {
    toastShow.value = true
  } else {
    toastShow.value = false
    emit('receiveProvinceMsg', provinceMsg.value);
  }
}

</script>

<style lang="scss"></style>